
package apibasej.http;

import java.util.ArrayList;


/**
 * http://code.google.com/p/apibasej/
 * 
 * @author Julio Azevedo Lessa - apibasej@gmail.com
 * 
 */
public class LengthCalc {

	public static final int NEWLINE = 2;
	public static final int PARAMETER_LINE = 39;
	public static final int FILE_LINE = 52;
	public static final int CONTENT_TYPE_LINE = 14;

	private long length = 0;
	private int boundaryLength = 0;

	public long calculateContentLengthMultpart(ArrayList<Field> formFields, ArrayList<FileUp> files, int boundaryLength) {

		this.boundaryLength = boundaryLength;
		
		// initialise
		length = 0;

		if (formFields != null && formFields.size() > 0) {
			calculateContentLengthFields(formFields);
		}

		if (files != null && files.size() > 0) {
			calculateContentLengthFiles(files);
		}

		if(length>0){// envia content length se não for enviar nada ??????
			// footer
			length += boundaryLength + 2;
			length += NEWLINE;
		}

		return length;
	}

	private void calculateContentLengthFields(ArrayList<Field> formInputFields) {

		for (Field f : formInputFields) {
			length += boundaryLength;
			length += NEWLINE;
			length += PARAMETER_LINE;
			length += f.getName().length();
			length += NEWLINE;
			length += NEWLINE;
			length += f.getValue().length();
			length += NEWLINE;
		}
	}

	private void calculateContentLengthFiles(ArrayList<FileUp> formFileFields) {

		for (FileUp f : formFileFields) {
			length += boundaryLength;
			length += NEWLINE;
			length += FILE_LINE;
			length += f.getName().length(); // parameter name
			length += f.getURLEncodedUploadName().length();
			length += NEWLINE;
			length += CONTENT_TYPE_LINE;
			length += f.getContentType().length();
			length += NEWLINE;
			length += NEWLINE;
			length += f.getFile().length();
			length += NEWLINE;
		}
	}
}
